const express = require('express')
const { insertData } = require('../db/sqlite')
const { hardwareIp } = require('../config/config')
const axios = require('axios')
const router = express.Router()
// --------------- 外部请求 ------
// 检测硬件连接，连上 WiFi 的时候请求这个接口
router.get('/connect-test', (req, res, next) => {
    console.log('硬件成功连接')
    res.send('suc')
})

// 存储数据接口，请求这个接口存储传感器数据
router.get('/record', function (req, res, next) {
    const query = req.query
    const sensorData = query['sensor-value']
    console.log('收到传感器信息 ', sensorData)
    insertData(sensorData)
        .then(() => {
            res.send('suc')
        })
})

// -------------- cms -----------
// 强行浇水
router.get('/go-water', function (req, res, next) {
    axios.get('http://' + hardwareIp + '/water')
        .then((response) => {
            // console.log('浇水请求返回', response.status)
            if (response.status == 200) {
                res.send('成功浇水')
            } else {
                res.send('浇水失败')
            }
        })
})

// 读取当前传感器数据
router.get('/read-sensor', function (req, res, next) {
    axios.get('http://' + hardwareIp + '/read-sensor')
        .then((response) => {
            // console.log('浇水请求返回', response.status)
            if (response.status == 200) {
                // console.log('返回', response.data)
                res.send('读取成功: ', response.data)
            } else {
                res.send('读取失败')
            }
        })

})
module.exports = router
